<?php
/* ------------------------------------------------------------------------
 * AION-KOREA Admin Control Panel
 *
 * @version 1.0
 * @author Taro6222 (AION-KOREA Admin CP main Developer)
 * @link http://redmine.aionkorea.org/projects/ak-admin-cp
 * @license http://creativecommons.org/licenses/by-nc-sa/3.0/deed.ko
 * @APM http://www.apachefriends.org/en/xampp.html
 *
------------------------------------------------------------------------ */

class daoUser
{
	/**
	 * Stores the instance of this class.
	 *
	 * @var -
	 */
	private static $instance = null;
	
	
	/**
	 * Returns the instance of the class.
	 * daoMember 클래스가 로딩되면 자동으로 호출되는 함수.
	 *
	 * @return -
	 */
	public static function getInstance()
	{
	    if ( is_null( self::$instance ) )
	    {
	        self::$instance = new self();
	    }
	    return self::$instance;
	}


	/**
	 * 계정이 존재할까?
	 * 
	 * @param unknown_type $account
	 */
	public static function checkUserId( $account )
	{
		$db = common::dbConnections(1);

		try
		{
			$account = trim( $account );

			$query = "
				SELECT *
				FROM account_data
				WHERE name = '$account'
			";
			$stmt = $db->query( $query );
			$rows = $stmt->fetch();
			if ( isset( $rows['name'] ) ) {
				return true;
			}
		}
		catch( Exception $e )
		{
			print "<b>daoUser->checkUserId</b><BR>{$query}";
			return false;
		}
	}

	/**
	 * 계정과 비번이 일치할까?
	 *
	 * @param str $account
	 * @param str $password
	 */
	public static function checkUserPassword( $account, $password )
	{
		$db = common::dbConnections(1);

		try
		{
			$account = trim( $account );
			$password = base64_encode( sha1( strtolower( trim( $password ) ), true ) );

			$query = "
				SELECT *
					FROM account_data
				WHERE name = '$account'
					AND password = '$password'
			";
			$stmt = $db->query( $query );
			$rows = $stmt->fetch();
			if ( isset( $rows['name'] ) ) {
				return true;
			}
		}
		catch( Exception $e )
		{
			print "<b>daoUser->checkUserPassword</b><BR>{$query}";
			return false;
		}
	}


	/**
	 * admincp 계정과 비번이 일치할까?
	 * access_level이 5 인지 확인.
	 *
	 */
	public static function admincpCheckAccount()
	{
		$db = common::dbConnections(1);

		try
		{
			$account = trim( $_POST['account'] );
			$password = base64_encode( sha1( strtolower( trim( $_POST['password'] ) ), true ) );

			$query = "
				SELECT *
					FROM account_data
				WHERE name = '$account'
					AND password = '$password'
			";
			$stmt = $db->query( $query );
			$rows = $stmt->fetch();

			$ret = '계정이 없거나 비밀번호가 틀림';
			if ( isset( $rows['name'] ) ) {
				if ( $rows['access_level'] != 5 ) {
					$ret = 'AdminCP 접근권한이 없습니다.';
				}
				else {
					//session 저장
					$_SESSION['admincp_session_id'] = $rows['id'];
					$_SESSION['admincp_session_name'] = $rows['name'];
					$_SESSION['admincp_session_access_level'] = $rows['access_level'];
					$_SESSION['admincp_session_membership'] = $rows['membership'];

					$ret = 'OK';
				}
			}
		}
		catch( Exception $e )
		{
			print "<b>daoUser->admincpCheckAccount</b><BR>{$query}";
			return false;
		}

		return $ret;
	}


	public static function getPlayers()
	{
		$dbGS = Zend_Registry::get('dbGS');
		$dbGS->setFetchMode(Zend_Db::FETCH_OBJ);

		$retArray = array();

		try
		{
			$account_id = $_SESSION['user_session_id'];
			$query = "SELECT
						P.id,
	                    P.name,
	                    P.race,
	                    P.player_class,
	                    P.exp,
	                    I.itemCount,
	                    P.online,
	                    I.itemUniqueId
					FROM players P
					JOIN inventory I ON P.id=I.itemOwner
					WHERE
						itemId = 182400001
					AND
						P.account_id = '{$account_id}'
			";
			//print '<pre>'.$query;
			$stmt = $dbGS->query( $query );
		}
		catch( Exception $e )
		{
			//print "<b>daoItems->getList</b><BR>--- " . $query . '<BR>--- ' . $e->getMessage();
			return array();
		}
		$i=0;
		foreach( $stmt as $obj )
		{
			$race = ( $obj->race == 'ASMODIANS' ) ? "마족" : "천족";
			$class = daoUser::getClass( $obj->player_class );

			$online = ( $obj->online == 1 ) ? " disabled=\"true\" title=\"온라인상태에서는 포인트 충전을 할 수 없습니다.\"" : "";
			$level = daoUser::getLevel( $obj->exp );

			$retArray[] = array(
				'id' => $obj->id,
            	'name' => $obj->name,
	            'race' => $race,
	            'class' => $class,
	            'level' => $level,
	            'kihna' => $obj->itemCount,
				'online' => $online,
				'itemUniqueId' => $obj->itemUniqueId,
            );
            $i++;
		}

		return $retArray;
	}


	public static function myPoint()
	{
		$db = Zend_Registry::get('db');

		$account_id = $_SESSION['user_session_id'];

		try
		{
			$query = "SELECT point
						FROM account_point
						WHERE account_id = $account_id
			";
			$stmt = $db->query( $query );
			$rows = $stmt->fetch();
			$num = ( $rows['point'] != '' ) ? $rows['point'] : 0;

			return $num;
		}
		catch( Exception $e )
		{
			print "<b>daoUser->myPoint</b><BR>" . $query . '<br>' . $e->getMessage();
			return false;
		}
	}


	public static function pointCharge()
	{
		$db = Zend_Registry::get('db');
		$dbGS = Zend_Registry::get('dbGS');

		$account_id = $_SESSION['user_session_id'];

		$itemCount = $_POST['point'];
		$itemUniqueId = $_POST['id'];

		try
		{
			//query inventory
			$query1 = "SELECT itemCount
					FROM inventory
					WHERE itemUniqueId = $itemUniqueId
			";
			$stmt1 = $dbGS->query( $query1 );
			$row1 = $stmt1->fetch();

			$myPoint = $row1['itemCount'] - $itemCount;

			//update inventory
			$data = array(
				'itemCount' => $myPoint
			);
			$where['itemUniqueId = ?'] = $itemUniqueId;
			$n = $dbGS->update('inventory', $data, $where);
			unset( $where );

			//query account_point
			$query2 = "SELECT *
					FROM account_point
					WHERE account_id = $account_id
			";
			$stmt2 = $db->query( $query2 );
			$row2 = $stmt2->fetch();

			//update or insert account_point
			if ( $row2['point'] != '' ) {
				$myPoint = $row2['point'] + $itemCount;
				$data = array(
					'point' => $myPoint
				);
				$where['account_id = ?'] = $account_id;
				$n = $db->update('account_point', $data, $where);
				unset( $where );
			}
			else {
				$data = array(
					'account_id' => $account_id,
					'point' => $itemCount,
				);
				 
				$db->insert('account_point', $data);
			}

			return true;
		}
		catch( Exception $e )
		{
			print "<b>daoUser->pointCharge</b><BR>" . $query . '<br>' . $e->getMessage();
			return false;
		}
	}
}
